import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_各学历及总体_省外生源的生源地分布(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None,
    education: Optional[str] = None
) -> Dict[str, Any]:
    """
    各学历及总体，省外生源的生源地分布 - 指标计算函数
    
    ## 指标说明
    该指标用于统计省外生源中各个生源省的毕业生人数及占对应学历总人数的比值。
    可以按不同学历（本科、专科、硕士、博士）分别统计，也可以统计总体情况。
    返回数据包含各细分学历数据和汇总数据。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        education (Optional[str]): 学历筛选条件，可选值：本科毕业生/专科毕业生/硕士研究生/博士研究生
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159],
        "education": "本科毕业生"
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok", 
        "code": 0,
        "result": [
            {
                "group": "本科毕业生",
                "data": [
                    {
                        "province": "广东省",
                        "count": 120,
                        "ratio": 0.15
                    },
                    {
                        "province": "河南省",
                        "count": 100,
                        "ratio": 0.125
                    }
                ]
            },
            {
                "group": "总体",
                "data": [
                    {
                        "province": "广东省",
                        "count": 320,
                        "ratio": 0.16
                    },
                    {
                        "province": "河南省",
                        "count": 280,
                        "ratio": 0.14
                    }
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 各学历及总体，省外生源的生源地分布, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year 
        FROM dp_njc.client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}")

        # 2. 计算 shard_tb_key
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 定义标准学历列表
        educations = ["本科毕业生", "专科毕业生", "硕士研究生", "博士研究生"]
        
        # 4. 如果指定了学历，则只计算该学历
        if education and education in educations:
            educations = [education]
        
        result = []
        
        # 5. 计算各学历情况
        for edu in educations:
            # 查询该学历的省外生源分布
            sql = f"""
            SELECT 
                birth_province, 
                count(*) as count, 
                count(*)/(SELECT count(*) 
                          FROM dim_client_target_baseinfo_student_calc_{item_year} 
                          WHERE shard_tb_key = %s 
                          AND education = %s) AS ratio_val
            FROM dim_client_target_baseinfo_student_calc_{item_year}
            WHERE shard_tb_key = %s
              AND birth_around = '省外生源'
              AND education = %s
            GROUP BY birth_province
            ORDER BY ratio_val DESC
            """
            data = db.fetchall(sql, (shard_tb_key, edu, shard_tb_key, edu))
            
            if data:
                result.append({
                    "group": edu,
                    "data": [{
                        "province": item["birth_province"],
                        "count": int(item["count"]),
                        "ratio": float(item["ratio_val"])
                    } for item in data]
                })
        
        # 6. 计算总体情况
        total_sql = f"""
        SELECT 
            birth_province, 
            count(*) as count, 
            count(*)/(SELECT count(*) 
                      FROM dim_client_target_baseinfo_student_calc_{item_year} 
                      WHERE shard_tb_key = %s) AS ratio_val
        FROM dim_client_target_baseinfo_student_calc_{item_year}
        WHERE shard_tb_key = %s
          AND birth_around = '省外生源'
        GROUP BY birth_province
        ORDER BY ratio_val DESC
        """
        total_data = db.fetchall(total_sql, (shard_tb_key, shard_tb_key))
        
        if total_data:
            result.append({
                "group": "总体",
                "data": [{
                    "province": item["birth_province"],
                    "count": int(item["count"]),
                    "ratio": float(item["ratio_val"])
                } for item in total_data]
            })

        logger.info(f"指标 '各学历及总体，省外生源的生源地分布' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result
        }

    except Exception as e:
        logger.error(f"计算指标 '各学历及总体，省外生源的生源地分布' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 各学历及总体，省外生源的生源地分布",
            "code": 500,
            "error": str(e)
        }